<?php

use Illuminate\Database\Capsule\Manager as DB;

class MembersController extends CCommonController
{
    public function indexAction()
    {
        $this->_view->display('members/index.html');
    }

    public function coinfoAction()
    {
        if(!$this->isPost()) {
            $dataset = (new companyModel)->find($this->user->company_id);
            $this->_view->assign('dataset', $dataset);
            $this->_view->assign('catalog', DB::table('catalog')->where('up', 0)->pluck('name', 'id'));
            $this->_view->assign('province', DB::table('sys_city')->where('up', 0)->pluck('name', 'id'));
            if ($dataset->province_id > 0) {
                $this->_view->assign('city', DB::table('sys_city')->where('up', $dataset->province_id)->pluck('name', 'id'));
                if ($dataset->city_id > 0) {
                    $this->_view->assign('district', DB::table('sys_city')->where('up', $dataset->city_id)->pluck('name', 'id'));
                }
            }
            $this->_view->display('members/coinfo.html');
        }else{
            do {
                #更新公司主信息
                $companyRows = $this->postData;
                $roles       = [
                    'city_id'       => ['role' => "required|gt:0", 'msg' => '所属地区'],
                    'name'          => ['role' => "required", 'msg' => '公司名称'],
                    'catalog_id'    => ['role' => "required", 'msg' => '所属行业'],
                    'introduce'     => ['role' => "required", 'msg' => '公司简介'],
                    'main_products' => ['role' => "required", 'msg' => '主营产品'],
                ];
                Validate::check($companyRows, $roles);
                $companyRows['updated_at'] = date('Y-m-d H:i:s');
                unset($companyRows['name'], $companyRows['code'], $companyRows['status'], $companyRows['db']);
                $this->cleanTableColumn('company', $companyRows);
                DB::table('company')->where('id', $this->user->company_id)->update($companyRows);
                #更新账号副信息
                $membersinfoRows = $this->postData['members_info'];
                $roles           = [
                    'contact' => ['role' => "required", 'msg' => '联系人'],
                    'tel'     => ['role' => "required", 'msg' => '联系电话'],
                    'qq'      => ['role' => "required", 'msg' => 'QQ'],
                    'email'   => ['role' => "required", 'msg' => '邮箱'],
                ];
                Validate::check($membersinfoRows, $roles);
                unset($membersinfoRows['company_id']);
                $this->cleanTableColumn('members_info', $membersinfoRows);
                DB::table('members_info')->where('company_id', $this->user->company_id)->update($membersinfoRows);
                #更新公司副信息
                $infoRows = $this->postData['info'];
                $roles    = [
                    'full_name'      => ['role' => "required", 'msg' => '公司全称'],
                    'operation_mode' => ['role' => "required", 'msg' => '经营模式'],
                    'business_type'  => ['role' => "required", 'msg' => '公司类型'],
                ];
                Validate::check($infoRows, $roles);
                unset($infoRows['company_id'], $infoRows['audit_company'], $infoRows['audit_members'], $infoRows['audit_email'], $infoRows['audit_phone']);
                $this->cleanTableColumn('company_info', $infoRows);
                DB::table('company_info')->where('company_id', $this->user->company_id)->update($infoRows);
                $auth = new Auth(_CookieKey_);
                $auth->logo = $companyRows['logo'];
                $result = [
                    'ret' => 0,
                    'msg' => '操作成功',
                ];
            } while (FALSE);
            json($result);
        }
    }

    public function authAction()
    {
        $this->_view->display('members/auth.html');
    }

    public function awardAction()
    {
        $this->_view->display('members/award.html');
    }

    public function issueAction()
    {
        $dba = 'products_' . $this->user->db;
        $dbb = 'products_info_' . $this->user->db;
        if ($this->isPost()) {
            $inputs = $this->postData;
            $roles  = [
                'title'  => ['role' => 'required', 'msg' => '标题'],
                'detail' => ['role' => 'required', 'msg' => '内容描述'],
            ];
            Validate::check($inputs, $roles);
            $class = '';
            if($inputs['cat_level1']>0){
                $class .= DB::table('catalog')->where('id', $inputs['cat_level1'])->value('name');
            }
            if($inputs['cat_level2']>0){
                $class .= ' > '.DB::table('catalog')->where('id', $inputs['cat_level2'])->value('name');
            }
            if($inputs['cat_level3']>0){
                $class .= ' > '.DB::table('catalog')->where('id', $inputs['cat_level3'])->value('name');
            }
            $logo = $images = '';
            preg_match_all("#<img(?:[^>]*)src=('|\")([^'\"]+)\\1#msix", $inputs['detail'], $allImg);
            if(isset($allImg[2])&&!empty($allImg[2])){
                $logo = $allImg[2][0];
                $images = implode(',', $allImg[2]);
            }

            try {
                DB::beginTransaction();
                $productsRow     = [
                    'company_id' => $this->user->company_id,
                    'title'      => $inputs['title'],
                    'logo'       => $logo,
                    'class'      => $class,
                    'cat_level1' => $inputs['cat_level1'],
                    'cat_level2' => $inputs['cat_level2'],
                    'cat_level3' => $inputs['cat_level3'],
                    'price'      => $inputs['price'],
                    'keywords'   => $inputs['keywords'],
                    'created_at' => date('Y-m-d H:i:s'),
                ];
                if($inputs['id']>0){
                    if(DB::table($dba)->where('company_id', $this->company_id)->whereIn('status', [0, 3])->where('id', $inputs['id'])->doesntExist()){
                        ret(2, '未找到匹配的记录');
                    }
                    DB::table($dba)->where('id', $inputs['id'])->update($productsRow);
                    $products_id = $inputs['id'];
                    $productsInfoRow = [
                        'products_id' => $products_id,
                        'images'      => $images,
                        'params'      => json_encode($inputs['params'], JSON_UNESCAPED_UNICODE),
                        'detail'      => $inputs['detail'],
                    ];
                    DB::table($dbb)->where('products_id', $products_id)->update($productsInfoRow);
                }else {
                    $products_id = DB::table($dba)->insertGetId($productsRow);
                    $productsInfoRow = [
                        'products_id' => $products_id,
                        'images'      => $images,
                        'params'      => json_encode($inputs['params'], JSON_UNESCAPED_UNICODE),
                        'detail'      => $inputs['detail'],
                    ];
                    DB::table($dbb)->insert($productsInfoRow);
                }
                DB::commit();
                ret(0, '操作成功');
            } catch (Throwable $t) {
                DB::rollback();
                ret('1', '操作失败，请重试');
            }
        }
        $id = $this->get('id/d', 0);
        if ($id > 0) {
            $map    = [[$dba . '.company_id', $this->user->company_id], ['id', $id]];
            $params = DB::table($dba)->join($dbb, $dba . '.id', '=', $dbb . '.products_id')->where($map)->first();
            $params->params = empty($params->params) ? [] : json_decode($params->params, true);
            if($params->cat_level1>0) {
                $catalog2 = DB::table('catalog')->where('up', $params->cat_level1)->orderBy('sortorder', 'desc')->pluck('name', 'id');
            }
            if($params->cat_level2>0) {
                $catalog3 = DB::table('catalog')->where('up', $params->cat_level2)->orderBy('sortorder', 'desc')->pluck('name', 'id');
            }
        } else {
            $catalog2 = [];
            $catalog3 = [];
            $params = [
                'id'         => '',
                'title'      => '',
                'class'      => '',
                'cat_level1' => 0,
                'cat_level2' => 0,
                'cat_level3' => 0,
                'price'      => '',
                'keywords'   => '',
                'status'     => 0,
                'params'     => [],
                'detail'     => '',
            ];
        }
        $catalog1 = DB::table('catalog')->where('up', 0)->orderBy('sortorder', 'desc')->pluck('name', 'id');
        $this->_view->assign('catalog1', json_encode($catalog1, JSON_UNESCAPED_UNICODE));
        $this->_view->assign('catalog2', json_encode($catalog2, JSON_UNESCAPED_UNICODE));
        $this->_view->assign('catalog3', json_encode($catalog3, JSON_UNESCAPED_UNICODE));
        $this->_view->assign('params', json_encode($params, JSON_UNESCAPED_UNICODE));
        $this->_view->display('members/issue.html');
    }

    public function previewAction()
    {
        $dba = 'products_' . $this->user->db;
        $dbb = 'products_info_' . $this->user->db;
        $id = $this->get('id/d', 0);
        if ($id > 0) {
            $map    = [[$dba . '.company_id', $this->user->company_id], ['id', $id]];
            $params = DB::table($dba)->join($dbb, $dba . '.id', '=', $dbb . '.products_id')->where($map)->first();
            $params->params = empty($params->params) ? [] : json_decode($params->params, true);
            $params->company = (new companyModel)->where('id', $params->company_id)->first()->toArray();
            $params->desc   = mb_substr(strip_tags($params->detail), 0, 200);
        }
        $this->_view->assign('dataset', object_to_array($params));
        #dump( object_to_array($params)); exit;
        $this->_view->display('members/preview.html');
    }

    public function infodelAction(){
        $id = $this->get('id/d', 0);
        $dba = 'products_' . $this->user->db;
        $dbb = 'products_info_' . $this->user->db;
        if(DB::table($dba)->where('company_id', $this->company_id)->whereIn('status', [0, 3])->where('id', $id)->doesntExist()){
            ret(2, '未找到匹配的记录');
        }
        try {
            DB::beginTransaction();
            DB::table($dba)->where('company_id', $this->company_id)->whereIn('status', [0, 3])->where('id', $id)->delete();
            DB::table($dbb)->where('products_id', $id)->delete();
            DB::commit();
            ret(0, '操作成功');
        } catch (Throwable $t) {
            DB::rollback();
            ret(1, '操作失败，请重试');
        }
    }

    public function infolistsAction()
    {
        if($this->isPost()){
            $dba = 'products_' . $this->user->db;
            $query = DB::table($dba)->where('company_id', $this->user->company_id);
            if ($this->get('status')!=='') {
                $query = $query->where('status', $this->get('status'));
            }
            $total = $query->count();
            $sort  = $this->get('sort', 'created_at');
            $order = $this->get('order', 'desc');
            $query = $query->orderBy($sort, $order);
            $page  = $this->get('page');
            if (!empty($page)) {
                $limit  = $this->get('size', 10);
                $offset = ($page - 1) * $limit;
                $query  = $query->offset($offset)->limit($limit);
            }
            $rows = $query->get();
            foreach ($rows as $k=>$v){
                $v->link = '/productsinfo/' . base64_encode($this->user->db . '-' . $v->id) . '.html';
            }
            json(['ret' => 0, 'msg' => '获取列表', 'data' => ['total' => $total, 'rows' => $rows]]);
        }else {
            $this->_view->display('members/infolists.html');
        }
    }

    public function templateAction()
    {
        $this->_view->display('members/template.html');
    }

    public function feedbackAction()
    {
        $this->_view->display('members/feedback.html');
    }

    public function helpAction()
    {
        $this->_view->display('members/help.html');
    }

    public function profileAction()
    {
        if ($this->isPost()) {
            $membersinfoRows = $this->postData;
            $roles           = [
                'contact' => ['role' => "required", 'msg' => '联系人'],
                'qq'      => ['role' => "required", 'msg' => 'QQ'],
                'email'   => ['role' => "required", 'msg' => '邮箱'],
            ];
            Validate::check($membersinfoRows, $roles);
            unset($membersinfoRows['company_id']);
            $this->cleanTableColumn('members_info', $membersinfoRows);
            DB::table('members_info')->where('members_id', $this->user->user_id)->update($membersinfoRows);
            ret(0, '操作成功');
        } else {
            $dataset = (new membersModel)->find($this->user->user_id);
            $this->_view->assign('dataset', $dataset);
            $this->_view->display('members/profile.html');
        }
    }

    public function storeAction()
    {
        $this->_view->display('members/store.html');
    }

    public function accountAction()
    {
        $dataset = (new membersModel)->find($this->user->user_id);
        $dataset->phone = substr($dataset->phone, 0, 4) . '****' . substr($dataset->phone, -3);
        $dataset->info->email = $dataset->info->email ? substr($dataset->info->email, 0, 4) . '****' . substr($dataset->info->email, -3) : '';
        $this->_view->assign('phone', $dataset->phone);
        $this->_view->assign('email', $dataset->info->email);
        $this->_view->display('members/account.html');
    }

    public function aboutusAction()
    {
        $this->_view->display('members/aboutus.html');
    }

    public function joinusAction()
    {
        $this->_view->display('members/joinus.html');
        #$this->_view->display( strtolower($this->controller.'/'.$this->method.'.'.$this->config['application']['view']['ext']) );
    }

    public function passwordAction()
    {
        if ($this->isPost()) {
            $membersinfoRows = $this->postData;
            $roles           = [
                'old_password'  => ['role' => "required", 'msg' => '旧密码'],
                'new_password'  => ['role' => "required", 'msg' => '新密码'],
                're_password'   => ['role' => "required|eq:".$membersinfoRows['new_password'], 'msg' => '重复密码'],
            ];
            Validate::check($membersinfoRows, $roles);
            $old_password = DB::table('members')->where('id', $this->user->user_id)->value('password');
            if($old_password!==md5($membersinfoRows['old_password'])){
                ret(2, '旧密码不正确');
            }
            DB::table('members')->where('id', $this->user->user_id)->update(['password'=>md5($membersinfoRows['new_password'])]);
            ret(0, '操作成功');
        } else {
            $this->_view->display('members/password.html');
        }
    }

    public function vipAction()
    {
        $this->_view->display('members/vip.html');
    }

}
